﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using CPlatePrintSys.Annotation.Converters;
using CPlatePrintSys.Annotation.Events;
using CPlatePrintSys.Annotation.Models;
using CPlatePrintSys.Domain.Events;
using CPlatePrintSys.Infrastructure;
using netDxf;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace CPlatePrintSys.Annotation.ViewModels
{
    
    public class DxfAnnotationViewModel : BindableBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;
        private string _controlId;

        public DelegateCommand<string> AnnotationCommand { get; private set; }

        public string ControlId { get; set; }

        public string MirrorControlId { get; set; }

        public string CurrentDxfDocumentName { get; private set; } = string.Empty;

        // 新增：当前活动的控件ID
        private string _activeControlId;
        public string ActiveControlId
        {
            get => _activeControlId;
            set => SetProperty(ref _activeControlId, value);
        }

        // 简化：移除复杂的控件状态管理，使用统一的全局状态
        // 新增：防止事件重复发送的标志位
        private bool _isSendingEvent = false;

        // 修改：基于当前活动控件的模式状态
        private bool _isInAddMode = false;
        public bool IsInAddMode
        {
            get => _isInAddMode;
            set
            {
                if (SetProperty(ref _isInAddMode, value))
                {
                    OnAnnotationChanged();
                }
            }
        }

        private bool _isInEditMode = false;
        public bool IsEditMode
        {
            get => _isInEditMode;
            set
            {
                if (SetProperty(ref _isInEditMode, value))
                {
                    OnAnnotationChanged();
                }
            }
        }

        private bool _isInDeletingMode = false;
        public bool IsInDeletingMode
        {
            get => _isInDeletingMode;
            set
            {
                if (SetProperty(ref _isInDeletingMode, value))
                {
                    OnAnnotationChanged();
                }
            }
        }

        private string _subTitle = string.Empty;
        public string SubTitle
        {
            get { return _subTitle; }
            set { SetProperty(ref _subTitle, value); }
        }

        public DelegateCommand BackToHomeCommand { get; private set; }

        public DelegateCommand SaveCommand { get; private set; }

        public DxfAnnotationViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _regionManager = regionManager;
            // ControlId 由View初始化后赋值

            SubTitle = "图纸标注";

            BackToHomeCommand = new DelegateCommand(ExecuteBackCommand);
            SaveCommand = new DelegateCommand(SaveAnnotation);

            this._eventAggregator.GetEvent<DisplayDxfPart>().Subscribe(OnDisplayDxfPart);
        }


        // 简化：设置活动控件的方法
        public void SetActiveControl(string controlId)
        {
            // 直接设置活动控件，不保存状态
            ActiveControlId = controlId;
            
            // 向所有控件发送当前的编辑模式事件，确保状态同步
            SendCurrentModeToActiveControl();
        }

        // 新增：强制同步所有控件的编辑模式状态
        public void SyncAllControlsState()
        {
            SendCurrentModeToActiveControl();
        }

        // 简化：向当前活动控件发送编辑模式事件
        private void SendCurrentModeToActiveControl()
        {
            if (_isSendingEvent)
                return;

            // 防止重复发送事件
            _isSendingEvent = true;
            
            try
            {
                // 确定当前的编辑模式
                EditingMode currentMode = EditingMode.None;
                if (_isInEditMode)
                    currentMode = EditingMode.Editing;
                else if (_isInAddMode)
                    currentMode = EditingMode.Adding;
                else if (_isInDeletingMode)
                    currentMode = EditingMode.Deleting;

                // 向所有控件发送编辑模式事件，确保状态同步
                // 先发送给normal控件
                this._eventAggregator.GetEvent<EditAnnotationEvent>().Publish(new EditAnnotationEventArgs { ControlId = "normal", Mode = currentMode });
                
                // 再发送给mirror控件
                this._eventAggregator.GetEvent<EditAnnotationEvent>().Publish(new EditAnnotationEventArgs { ControlId = "mirror", Mode = currentMode });
            }
            finally
            {
                // 确保标志位被重置
                _isSendingEvent = false;
            }
        }

        private void OnAnnotationChanged()
        {
            // 简化：只向当前活动控件发送编辑模式事件
            SendCurrentModeToActiveControl();
        }

        private void OnDisplayDxfPart(DisplayDxfPartArgs args)
        {
            this.CurrentDxfDocumentName = args.Document.Name;
        }

        private void ExecuteBackCommand()
        {
            // 发布清理事件，通知所有控件清理其内部状态
            this._eventAggregator.GetEvent<ClearAnnotationCacheEvent>().Publish(new ClearAnnotationCacheEventArgs
            {
                Reason = "用户返回列表视图",
                ForceClearAll = true
            });
            
            // 清理ViewModel的状态
            IsInAddMode = false;
            IsEditMode = false;
            IsInDeletingMode = false;
            ActiveControlId = null;
            
            System.Diagnostics.Debug.WriteLine("=== 缓存清理完成，导航到主窗口 ===");
            
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "MainWindow");
        }


        private void SaveAnnotation()
        {
            var annotationManager = AnnotationManager.Instance;
            
            // 通知所有AnnotationDisplayerControl同步数据
            // 通过事件聚合器发布同步事件
            this._eventAggregator.GetEvent<SyncToDxfEvent>().Publish(new SyncToDxfEventArgs());
            
            // 发布保存事件
            this._eventAggregator.GetEvent<SaveAnnotationEvent>().Publish(CurrentDxfDocumentName);
        }

    }
}
